package com.ljx.offer;

import org.junit.Test;

import java.util.LinkedList;

/**
 * @author 李捷禧
 * Date: 2023/3/20
 * ClassName: C_58
 */

public class C_58 {
    /**
     * 参考题解，解法不一样
     * 递归会更好
     * 逻辑，解答独立完成
     * @param s
     * @return
     */
    public String reverseWords(String s) {
        s = s.trim();
        char[] arr = s.toCharArray();
        StringBuffer sb =new StringBuffer();
//        for (int i = 0; i < s.length(); i++) {
//            System.out.println(arr[i]);
//        }
//        return s;
        int j = s.length();
        for (int i = s.length() - 1; i >=0 ; i--) {
            if (i==0){
                sb.append(s.substring(i, j));
            }
            else if(arr[i] == ' ') {
                if(arr[i+1] != ' '){
                    sb.append(s.substring(i+1, j));
                    sb.append(' ');
                }
                j = i;
            }
        }
        return sb.toString().trim();

    }

    @Test
    public void test(){
        String str = "I am  ljx";
        System.out.println(reverseWords(str));
    }

}
